// -----------------------------------------------------------------------------
//                   G O L A N G   S P E C I F I C A T I O N
// -----------------------------------------------------------------------------
// NAME
//
//  xymonc.go  -  xymon client by Go language.
//
// REVISION HISTORY
//     12/30/2013   T.J. Yang init.
//
// USAGE
//
//
// DESCRIPTION
// 
//
// 
// TODOs
//  1. Improve Makefile syntax.
// REFERENCES:
// 1. https://gobyexample.com/
// ---------------------------- CONSTANT  DECLARATION ---------------------------


package main

// ---------------------------- GO PACKAGES   ---------------------------
// import golang modules/packages 
import (
	"fmt"        // to use fmt.Fprintf type of function.
	"io/ioutil"
	"net"
	"os"
)

// ---------------------------- FUNCTIONS    ---------------------------
// WHAT: Generic error checking and error message report function.
func checkError(err error) {

	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
		os.Exit(1)
	}
}


// ---------------------------- MAIN           ---------------------------
func main() {

// ---------------------------- VARIABLES DECLARATION ---------------------------        
        var usage string = "Usage: %s host:port \n"
        var httpheader  string = "HEAD / HTTP/1.0\r\n\r\n"


	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr,usage, os.Args[0])
		os.Exit(1)
	}
	service := os.Args[1]

	tcpAddr, err := net.ResolveTCPAddr("tcp", service)
	checkError(err)

	conn, err := net.DialTCP("tcp", nil, tcpAddr)
	checkError(err)

        // case port 80
	_, err = conn.Write([]byte(httpheader))
	checkError(err)
        // case port 80
	result, err := ioutil.ReadAll(conn)
	checkError(err)
	fmt.Println(string(result))

	os.Exit(0)
}

